package com.lwq.im.chartdemo.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.lwq.im.chartdemo.bean.CommonResult;
import com.lwq.im.chartdemo.bean.Message;
import com.lwq.im.chartdemo.session.OnlineSession;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class ChartController {


    @Autowired
    private OnlineSession onlineSession;

    @RequestMapping("onlieUserId")
    public CommonResult getOnlieSession(){
        return CommonResult.success(onlineSession.getOnlineUserId());
    }

    @PostMapping("sendMessge")
    public CommonResult sendMessge(@RequestBody Message message){

        Map<String, Collection<Channel>> onlineSession = this.onlineSession.getOnlineSession();
        if (CollectionUtil.isEmpty(onlineSession)){
            return CommonResult.success();
        }
        Collection<Channel> channels = onlineSession.get(message.getTo());
        if (CollectionUtil.isEmpty(channels)){
            return CommonResult.success();
        }
        channels.forEach(channel -> {
            channel.writeAndFlush(message);
        });
        return CommonResult.success();
    }
}
